package de.hpi.generator.model;

import de.hpi.generator.config.TableModel;
import java.io.IOException;

public class Table {

    private String aName;

    public String getName() {
        return aName;
    }
    private int aMinRowNumbers = 0;

    public int getMinRowNumbers() {
        return aMinRowNumbers;
    }
    private Database aOwner;

    public Database getOwner() {
        return aOwner;
    }
    public boolean canBeIncreased = true;
    private ColumnsCollection aColumns = new ColumnsCollection(this);

    public ColumnsCollection getColumns() {
        return aColumns;
    }

    public Table(TableModel aTableModel, Database aOwner) {
        this.aName = aTableModel.name;
        this.aMinRowNumbers = aTableModel.rowNumbers;
        this.aOwner = aOwner;
    }

    public Column findColumnByName(String aColumnName) {
        for (Column aColumn : aColumns) {
            if (aColumn.getName().compareToIgnoreCase(aColumnName) == 0) {
                return aColumn;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        String result = String.format("{name: %s, rowNumbers: %d \n \tcolumns:[ \n", getName(), getMinRowNumbers());
        String aColumnsString = "";
        for (Column aColumn : getColumns()) {
            aColumnsString += "\t\t" + aColumn.toString();
        }
        return result + aColumnsString + "\t]}\n";
    }

    public String getWorkingDirectoryPath() {
        return this.aOwner.getWorkingDirectoryPath() + "\\" + this.aName;
    }

    public void openForRead() throws Exception {
        aColumns.openForRead();
    }

    public void closeAfterRead() throws Exception {
        aColumns.closeAfterRead();
    }

    public void balanceColumnsValues() throws Exception {
        int aMaxNumberOfDependentValues = aColumns.getMaxNumberOfValues();
        if (aMaxNumberOfDependentValues < aMinRowNumbers) {
            aMaxNumberOfDependentValues = aMinRowNumbers;
        }
        
        for (Column aColumn : aColumns) {
            aColumn.generateAdditionalExtendedDistribution(aMaxNumberOfDependentValues);
        }
    }
}
